package com.eco.fanliapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.dao.GoodsFreeMapper;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.job.sytimeperiodgoodsjob.JobSQKBTimeLimitSecondKill;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.DateUtils;
import com.eco.fanliapp.utils.HttpUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.*;

@Service
public class JobSQKBTimeLimitSecondKillServiceImpl implements IJobSQKBTimeLimitSecondKillService {

    private static final Logger logger = LoggerFactory.getLogger(JobSQKBTimeLimitSecondKill.class);

    @Autowired
    private ISyTimePeriodService syTimePeriodService;
    @Autowired
    private ISyTimePeriodGoodsService syTimePeriodGoodsService;
    @Autowired
    private IAppGoodsService appGoodsService;
    @Autowired
    private ISyLabelTypeService syLabelTypeService;
    @Autowired
    private ISyLabelGoodsService syLabelGoodsService;
    @Autowired
    private GoodsFreeMapper goodsFreeMapper;

    /**
     * 抓取省钱快报限时秒杀数据
     *
     * @param isOnlyNowTime 是否只更新最近的时间
     */
    public void getSQKBData(boolean isOnlyNowTime) {
        try {

            int y = 0;
            //省钱快报url地址
            String url = "https://m.sqkb.com/v2/seckill/home/eventList";
            RestTemplate restTemplate = new RestTemplate();
            //获取省钱快报秒杀时间段数据
            String res = restTemplate.getForObject(url, String.class);
            JSONObject jsonObject = JSONObject.parseObject(res);
            JSONObject jsonObjectData = jsonObject.getJSONObject("data").getJSONObject("data");
            //限时秒杀时间段
            JSONArray event_list = jsonObjectData.getJSONArray("event_list");
            JSONArray coupon_list = jsonObjectData.getJSONArray("coupon_list");

            //查询所有时间段
            QueryWrapper<SyTimePeriod> queryWrapper = new QueryWrapper();
            queryWrapper.eq("enable", 1);
            queryWrapper.eq("deleted", 0);
            List<SyTimePeriod> syTimePeriods = syTimePeriodService.list(queryWrapper);
            Map<String, Integer> periods = new HashMap<>();
            for (SyTimePeriod syTimePeriod : syTimePeriods) {
                periods.put(syTimePeriod.getPeriodTime() + "", syTimePeriod.getTableId());
            }

            Date dateZeroStartTime = DateUtils.getZeroStartTimeByDate(DateUtils.updateDayByDate(new Date(), -2));
            Date dateZeroEndTime = DateUtils.getZeroEndTimeByDate(DateUtils.updateDayByDate(new Date(), 2));
            //查询数据库中已经存在的限时秒杀数据（两天内）
            QueryWrapper<SyTimePeriodGoods> goodsQueryWrapper = new QueryWrapper();
            goodsQueryWrapper.eq("enable", 1);
            goodsQueryWrapper.eq("deleted", 0);
            goodsQueryWrapper.ge("period_goods_time", dateZeroStartTime);
            goodsQueryWrapper.le("period_goods_time", dateZeroEndTime);
            List<SyTimePeriodGoods> goodsSyTimePeriods = syTimePeriodGoodsService.list(goodsQueryWrapper);

            //已经存在数据中的限时秒杀数据，用于判断更新或者新增数据
            Map<String, Integer> itmeIds = new HashMap<>();
            for (SyTimePeriodGoods syTimePeriodGoods : goodsSyTimePeriods) {
                itmeIds.put(syTimePeriodGoods.getItemId() + "_" + DateUtils.date2Str(syTimePeriodGoods.getPeriodGoodsTime(), DateUtils.DATE_FORMAT_YYYYMMDDHHMMSS), syTimePeriodGoods.getTableId());
            }

            //限时秒杀中今日爆款数据（在列表上面共三条）
            List<String> itemIdHots = new ArrayList<>();
            if (coupon_list != null && coupon_list.size() > 0) {
                for (int i = 0; i < coupon_list.size(); i++) {
                    JSONObject job = coupon_list.getJSONObject(i);
                    String itemId = job.getString("item_id");
                    itemIdHots.add(itemId);
                }
            }

            //查询秒杀标签
            QueryWrapper<SyLabelType> queryWrapper11 = new QueryWrapper<>();
            queryWrapper11.like("label_name", "秒杀");
            queryWrapper11.eq("enable", 1);
            queryWrapper11.eq("deleted", 0);
            List<SyLabelType> list = syLabelTypeService.list(queryWrapper11);

            SyLabelType syLabelType = list.get(0);

            //限时秒杀商品排序（前三条会是爆款商品）
            int sortNum = 0;
            if (event_list.size() > 0) {
                //循环时间段
                for (int i = 0; i < event_list.size(); i++) {
                    // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                    JSONObject job = event_list.getJSONObject(i);

                    String title = job.getString("title");
                    Long start_time = job.getLong("start_time");
                    String event_id = job.getString("event_id");
                    Date todayStartTime = DateUtils.getZeroStartTimeByDate(new Date());
                    //只更新今天和之后的时间段商品
                    //20191109注释，更新昨天秒杀商品
//                    if (start_time * 1000 < DateUtils.datestr2LongByFormt(DateUtils.date2Str(todayStartTime,DateUtils.DATE_FORMAT_YYYYMMDDHHMMSS),DateUtils.DATE_FORMAT_YYYYMMDDHHMMSS)){
//                        continue;
//                    }
                    if (title.contains(":")) {
                        if (isOnlyNowTime) {
                            if (start_time * 1000 > System.currentTimeMillis() || start_time * 1000 < (System.currentTimeMillis() - 1000L * 60 * 60 * 2)) {
                                continue;
                            }
                        }

                        //当前时间段内请求省钱快报的数据
                        List<Long> allGoodsList = new ArrayList<>();
                        List<String> allGoodsListStr = new ArrayList<>();

                        //分页
                        int cc = 1;
                        //爆款数量控制在三条
                        int hotcakeNum = 0;
                        while (true) {
                            //查询时间段对应的商品
                            String goodsUrl = "https://m.sqkb.com/v2/seckill/home/homeEventInfo?event_id=" + event_id + "&current_event_id=3475&top_coupon_ids=&page=" + cc + "&stid_params={%22app%22:{%22page%22:%22h5_home_seckill%22,%22business%22:%22home_seckill%22,%22bid%22:%22%22,%22entrance%22:%22main_tab_home%22,%22extend%22:{%22seckill_id%22:3475,%22tab_pos%22:0,%22seckill_status%22:5,%22seckill_is_new%22:1}}}";
                            String goodsRes = HttpUtils.sendGet(goodsUrl, "");

                            JSONObject jsonObjectGoods = JSONObject.parseObject(goodsRes);
                            JSONObject jsonObjectDataGoods = jsonObjectGoods.getJSONObject("data").getJSONObject("data");


                            cc++;
                            if (cc > 10 || jsonObjectDataGoods == null || jsonObjectDataGoods.getJSONArray("coupon_list") == null || jsonObjectDataGoods.getJSONArray("coupon_list").size() <= 0) {
                                break;
                            }
                            JSONArray coupon_list_goods = jsonObjectDataGoods.getJSONArray("coupon_list");


                            if (coupon_list_goods.size() > 0) {

                                Map<String, SyLabelGoods> eventSylableGoodsMap = new HashMap<>();
                                Map<String, AppGoods> eventAppgoodsMap = new HashMap<>();
                                //商品表是否存在,标签表是否存在
                                List<String> itemids_event = new ArrayList<>();
                                for (int j = 0; j < coupon_list_goods.size(); j++) {
                                    JSONObject job_goods = coupon_list_goods.getJSONObject(j);
                                    Long item_id = job_goods.getLong("item_id");
                                    itemids_event.add(item_id + "");
                                    allGoodsList.add(item_id);
                                    allGoodsListStr.add(item_id + "");
                                }

                                if (itemids_event.size() > 0) {
                                    //已存在的商品
                                    QueryWrapper<AppGoods> appGoodsQueryWrapper = new QueryWrapper<>();
                                    appGoodsQueryWrapper.in("itemid", itemids_event);
                                    List<AppGoods> appGoodsList = appGoodsService.list(appGoodsQueryWrapper);
                                    if (appGoodsList != null && appGoodsList.size() > 0) {
                                        for (AppGoods appGoods : appGoodsList) {
                                            eventAppgoodsMap.put(appGoods.getItemid(), appGoods);
                                        }
                                    }
                                    //已存在标签的限时秒杀数据
                                    QueryWrapper<SyLabelGoods> syLabelGoodsQueryWrapper = new QueryWrapper<>();
                                    syLabelGoodsQueryWrapper.in("item_id", itemids_event);
                                    List<SyLabelGoods> syLabelGoodsList = syLabelGoodsService.list(syLabelGoodsQueryWrapper);
                                    if (syLabelGoodsList != null && syLabelGoodsList.size() > 0) {
                                        for (SyLabelGoods syLabelGoods : syLabelGoodsList) {
                                            eventSylableGoodsMap.put(syLabelGoods.getItemId(), syLabelGoods);
                                        }
                                    }
                                }

                                for (int j = 0; j < coupon_list_goods.size(); j++) {
                                    JSONObject job_goods = coupon_list_goods.getJSONObject(j);
                                    Long item_id = job_goods.getLong("item_id");
                                    String thumbnail_pic = job_goods.getString("thumbnail_pic");
                                    String raw_price = job_goods.getString("raw_price");
                                    String zk_price = job_goods.getString("zk_price");
//                            Long start_time_ = job_goods.getLong("start_time");
                                    String goods_title = job_goods.getString("title");

                                    JSONObject job_goods1 = job_goods.getJSONObject("rebate_super");
                                    Long quota = job_goods1.getLong("init_quota");
                                    Long sale_count = job_goods1.getLong("sale_count");
                                    Integer weight = job_goods1.getInteger("weight");

                                    AppGoods appGoods = new AppGoods();
                                    appGoods.setItemid(item_id.toString());
                                    AppGoods appGood = null;
                                    if (eventAppgoodsMap.keySet().contains(item_id + "")) {
                                        appGood = eventAppgoodsMap.get(item_id + "");
                                    } else {
                                        appGoodsService.addAppGoods(appGoods, -111);
                                        appGood = appGoodsService.findAppGoodsByItemId(item_id.toString());
                                    }
                                    //获取商品
                                    if (appGood == null) {
                                        logger.info("获取限制秒杀商品失败，商品不存在+{}+{}-{}", title, item_id, start_time);
                                        continue;
                                    }

                                    SyTimePeriodGoods syTimePeriodGoods = new SyTimePeriodGoods();

                                    sortNum++;
                                    //如果秒杀表存在改时间段内的商品，就更新
                                    if (itmeIds.keySet().contains(item_id + "_" + DateUtils.long2DatestrByFormt(start_time * 1000, DateUtils.DATE_FORMAT_YYYYMMDDHHMMSS))) {
                                        syTimePeriodGoods.setTableId(itmeIds.get(item_id + "_" + DateUtils.long2DatestrByFormt(start_time * 1000, DateUtils.DATE_FORMAT_YYYYMMDDHHMMSS)));
                                    }
//                                syTimePeriodGoods.setTopSerialNum(sortNum);
                                    syTimePeriodGoods.setItemId(item_id);

                                    syTimePeriodGoods.setTopSerialNum(weight);
                                    syTimePeriodGoods.setPeriodId(periods.get(title));
                                    syTimePeriodGoods.setPeriodTime(title);
                                    //省钱快报
                                    syTimePeriodGoods.setItemResonOne("SQKB");
                                    syTimePeriodGoods.setItemTitle(goods_title);
                                    syTimePeriodGoods.setItemPic(thumbnail_pic.replace("_400x400", ""));
                                    syTimePeriodGoods.setItemNum(quota + "");
                                    syTimePeriodGoods.setPeriodNum(sale_count + "");
                                    syTimePeriodGoods.setItemDesc(goods_title);
                                    syTimePeriodGoods.setEnable(1);
                                    syTimePeriodGoods.setDeleted(0);
                                    syTimePeriodGoods.setOriginalPrice(new BigDecimal(appGoods.getItemprice() == null ? "0" : appGoods.getItemprice()));
//                                syTimePeriodGoods.setDiscountPrice(new BigDecimal(zk_price == null ? "0" : zk_price));
                                    syTimePeriodGoods.setDiscountPrice(new BigDecimal(appGoods.getItemendprice() == null ? 0 : appGoods.getItemendprice()));
                                    syTimePeriodGoods.setPeriodGoodsTime(DateUtils.datestr2Date(DateUtils.long2DatestrByFormt(start_time * 1000, DateUtils.DATE_FORMAT_YYYYMMDDHHMMSS), DateUtils.DATE_FORMAT_YYYYMMDDHHMMSS));
//                                    syTimePeriodGoods.setDiscount("");
                                    syTimePeriodGoods.setAppointment(0);

                                    syTimePeriodGoods.setTkMoney(syTimePeriodGoods.getTkMoney());

                                    if (itemIdHots.contains(item_id + "")) {
                                        syTimePeriodGoods.setHotCake(1);
                                        hotcakeNum++;
                                    } else {
                                        if (hotcakeNum < 3) {
                                            syTimePeriodGoods.setHotCake(1);
                                            hotcakeNum++;
                                        }
                                    }

                                    syTimePeriodGoods.setItemPic(appGood.getItempic());
                                    syTimePeriodGoods.setItemDesc(appGood.getItemdesc());
                                    //原价
//                                log.info("商品原价{}",appGood.getItemprice());
                                    if (appGood.getItemprice() != null && !"".equals(appGood.getItemprice())) {
                                        syTimePeriodGoods.setOriginalPrice(BigDecimal.valueOf(Double.parseDouble(appGood.getItemprice())));
                                    }
                                    //折扣价
//                                log.info("商品折扣价{}",appGood.getItemendprice());
                                    if (appGood.getItemendprice() != null && !"".equals(appGood.getItemendprice())) {
                                        syTimePeriodGoods.setDiscountPrice(BigDecimal.valueOf(appGood.getItemendprice()));
                                    }
                                    syTimePeriodGoods.setTkMoney(new BigDecimal(appGood.getTkmoney() == null ? "0" : appGood.getTkmoney()));

                                    try {
                                        if (syTimePeriodGoods.getTableId() == null) {
                                            GoodsFree free = goodsFreeMapper.selectByGoodsId(appGoods.getItemid());
                                            if (free == null) {
                                                syTimePeriodGoodsService.save(syTimePeriodGoods);
                                                if (eventSylableGoodsMap.size() <= 0 || !eventSylableGoodsMap.keySet().contains(item_id + "")) {
                                                    //保存标签商品
                                                    SyLabelGoods labelGoods = new SyLabelGoods();
                                                    labelGoods.setItemId(item_id + "");
                                                    labelGoods.setLabelTypeId(syLabelType.getTableId().toString());
                                                    labelGoods.setLabelCode(syLabelType.getLabelCode());
                                                    syLabelGoodsService.save(labelGoods);
                                                }
                                            }
                                        } else {
                                            syTimePeriodGoodsService.updateById(syTimePeriodGoods);
                                        }
                                    } catch (Exception e) {
//                                    e.printStackTrace();
                                        logger.info("限时秒杀商品存入失败-itemid={}-time={}", item_id, start_time);
                                    }

                                }
                            }
                        }
                        //删除省钱快报已经删除的商品
                        if (allGoodsList.size() > 0) {
                            QueryWrapper<SyTimePeriodGoods> syTimePeriodGoodsQueryWrapper = new QueryWrapper<>();
//                        syTimePeriodGoodsQueryWrapper.in("item_id", allGoodsList);
                            syTimePeriodGoodsQueryWrapper.eq("period_goods_time", DateUtils.long2DatestrByFormt(start_time * 1000, DateUtils.DATE_FORMAT_YYYYMMDDHHMMSS));
                            List<SyTimePeriodGoods> syTimePeriodGoodsList = syTimePeriodGoodsService.list(syTimePeriodGoodsQueryWrapper);
                            for (SyTimePeriodGoods syTimePeriodGoods : syTimePeriodGoodsList) {
                                if (!allGoodsListStr.contains(syTimePeriodGoods.getItemId() + "")) {
                                    try {
                                        syTimePeriodGoodsService.removeById(syTimePeriodGoods.getTableId());
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }


                    } else {
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.info("获取秒杀商品鼠标错误");
        }
    }


    public static void main(String args[]) {
        String url = "https://m.sqkb.com/v2/seckill/home/eventList";
        RestTemplate restTemplate = new RestTemplate();
        String res = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(res);

//        JSONObject jsonObjectData = jsonObject.getJSONObject("data");
//
//        JSONArray jsonArray = jsonObjectData.getJSONObject("data").getJSONArray("event_list");
//
//
//        if(jsonArray.size()>0){
//            for(int i=0;i<jsonArray.size();i++){
//                JSONObject job = jsonArray.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
//                String event_id = job.getString("event_id");
//                String goodsUrl = "https://m.sqkb.com/v2/seckill/home/homeEventInfo?event_id="+event_id+"&current_event_id=3475&top_coupon_ids=&page=1&stid_params={%22app%22:{%22page%22:%22h5_home_seckill%22,%22business%22:%22home_seckill%22,%22bid%22:%22%22,%22entrance%22:%22main_tab_home%22,%22extend%22:{%22seckill_id%22:3475,%22tab_pos%22:0,%22seckill_status%22:5,%22seckill_is_new%22:1}}}";
//
//                String goodsRes = HttpUtils.sendGet(goodsUrl, "");
////                goodsUrl = URLEncoder.encode(goodsUrl);
////                String goodsRes = restTemplate.getForObject(goodsUrl, String.class);
//            }
//        }

    }
}
